package cn.shop.crontab.task;

import cn.shop.crontab.message.MessageUtil;
import cn.shop.msgs.OrderMsg;
import cn.shop.transcation.order.entity.Order;
import cn.shop.transcation.order.mapper.OrderMapper;
import cn.shop.utils.enums.OrderStatus;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author : 李一涵
 * @date : Created in 2022-2-27 14:52
 * @description :
 */
@Service
@Slf4j
public class OrderTimeCheckTask {

	@Resource
	private MessageUtil messageUtil;
	@Resource
	private OrderMapper mapper;

	private final static String SELECT = "select id, down_time from `order` where status = 2 and deleted = false order by create_time asc";
	private final static String UPDATE = "update `order` set status = 6, update_time = ? where id = ?";
	private final static String INSERT_INBOX = "insert into inbox(id, content, create_time, create_id) values(?, ?, ?, ?)";

	@Scheduled(cron = "0 * * * * ?")
	@Transactional(rollbackFor = Exception.class)
	public void checkOrder() {

		List<Order> list = mapper.selectList(Wrappers.<Order>lambdaQuery().eq(Order::getStatus, OrderStatus.PASSED).orderByAsc(Order::getAuditTime));


		LocalDateTime now = LocalDateTime.now();
		for (Order order : list) {
			//log.info("订单下线检查 当前时间：{}，下线时间：{}", now, order.getDownTime());
			if (now.isBefore(order.getDownTime())) {
				continue;
			}
			Order update = new Order();
			update.setId(order.getId());
			update.setStatus(OrderStatus.SOLD_OUT);
			int count = mapper.updateById(update);
			if (count > 0) {
				try {
					messageUtil.sendMessage(OrderMsg.TOPIC, OrderMsg.TAG, OrderMsg.start().id(order.getId()).time(now).status(OrderStatus.SOLD_OUT));
				} catch (Exception e) {
					log.warn("发送退回消息失败", e);
				}
				//jdbcTemplate.update(INSERT_INBOX, IdWorker.getId(), "您的订单已过公示期自动下架，物品原路退回，请到游戏内领取", LocalDateTime.now(), 0);
			}
		}
	}
}
